<?php

namespace app\models;

use Yii;
use yii\data\Pagination;
use yii\db\ActiveRecord;
/**
 * This is the model class for table "tb_article".
 *
 * @property integer $id
 * @property string $title
 * @property string $content
 * @property string $author
 * @property string $now
 *
 * @property TbFilecomment[] $tbFilecomments
 */
class TbArticle extends ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'tb_article';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['content'], 'string'],
            [['now'], 'safe'],
            [['title'], 'string', 'max' => 200],
            [['author'], 'string', 'max' => 20],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'title' => Yii::t('app', 'Title'),
            'content' => Yii::t('app', 'Content'),
            'author' => Yii::t('app', 'Author'),
            'now' => Yii::t('app', 'Now'),
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getTbFilecomments()
    {
        return $this->hasMany(TbFilecomment::className(), ['fileid' => 'id']);
    }

    /**
     * 最新五条最新记录
     * @param $username
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function selecttop5($username){
        $sql="select * from tb_article WHERE author='$username'  order by now desc limit 5  ";
        $r=TbArticle::findBySql($sql)->all();
        return $r;
    }

    /**
     * 根据账号查询全部文章
     * @param $username
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function selectnameAll($username){
        $public = TbArticle::find()->where(['author'=>$username]);
        //创建pagination 并对public进行分页设置
        $pagination =new Pagination([
            'defaultPageSize'=>10,
            'totalCount'=>$public->count(),
        ]);
        $countries =$public->orderBy('id')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
        $shuzu = array($countries,$pagination);
        return $shuzu;
    }
    /**
     * 查询全部文章
     * @param $username
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function selectAll(){
        $public = TbArticle::find();
        //创建pagination 并对public进行分页设置
        $pagination =new Pagination([
            'defaultPageSize'=>10,
            'totalCount'=>$public->count(),
        ]);
        $countries =$public->orderBy('now desc')
            ->offset($pagination->offset)
            ->limit($pagination->limit)
            ->all();
        $shuzu = array($countries,$pagination);
        return $shuzu;
    }

    /**
     * 根据ID查询文章
     */
    public static function selectid($id){
        return $id=self::find()->where(['id'=>$id])->one();
    }
}